package com.wing.purchase.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.common.enums.PurEnum;
import com.wing.product.service.DynamicService;
import com.wing.purchase.dao.PurchaseDeliveryRecordDao;
import com.wing.purchase.model.entity.PurchaseDeliveryRecord;
import com.wing.purchase.model.entity.PurchaseDeliveryRecordProduct;
import com.wing.purchase.model.entity.PurchaseOrder;
import com.wing.purchase.model.entity.PurchaseOrderDetail;
import com.wing.purchase.model.request.PurchaseDeliveryRecordForm;
import com.wing.purchase.model.response.PurchaseDeliveryRecordVO;
import com.wing.purchase.model.response.SupplierWaybillVo;
import com.wing.web.db.config.util.DynamicDataSource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 供应商发货记录-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class PurchaseDeliveryRecordServiceImpl extends ServiceImpl<PurchaseDeliveryRecordDao, PurchaseDeliveryRecord> implements PurchaseDeliveryRecordService {

    @Autowired
    private DynamicService dynamicService;
    @Autowired
    private PurchaseDeliveryRecordProductService purchaseDeliveryRecordProductService;
    @Autowired
    private PurchaseOrderService purchaseOrderService;
    @Autowired
    private PurchaseOrderDetailService purchaseOrderDetailService;

    @Override
    @Transactional(readOnly = false)
    public int add(PurchaseDeliveryRecordForm purchaseDeliveryRecordForm) {

        //校验

        PurchaseDeliveryRecord purchaseDeliveryRecord =new PurchaseDeliveryRecord();
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(PurchaseDeliveryRecord.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(purchaseDeliveryRecordForm, purchaseDeliveryRecord, copyOptions);

        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMdd");
        String code = dynamicService.getMaxCode("logistics_no", "pur_purchase_delivery_record");
        String day = simpleDateFormat.format(new Date());
        purchaseDeliveryRecord.setLogisticsNo("WL"+day+code);
        purchaseDeliveryRecord.setStatus(PurEnum.sendStatus.DQS.getCode());
        purchaseDeliveryRecord.setType(PurEnum.deliveryRecordTypes.CGDD.getCode());
        int i = baseMapper.insert(purchaseDeliveryRecord);
        if(i > 0){
            // 获取采购订单
            PurchaseOrder purchaseOrder = purchaseOrderService.getById(purchaseDeliveryRecord.getPurchaseOrderId());
            int skuNum = purchaseDeliveryRecordForm.getPurchaseDeliveryRecordProducts().size();
            List<PurchaseOrderDetail> orderDetails = new ArrayList<>();
            for(PurchaseDeliveryRecordProduct purchaseDeliveryRecordProduct :purchaseDeliveryRecordForm.getPurchaseDeliveryRecordProducts()){
                purchaseDeliveryRecordProduct.setPurchaseDeliveryRecordId(purchaseDeliveryRecord.getId());
                //扣除发货数量
                PurchaseOrderDetail orderDetailServiceById = purchaseOrderDetailService.getById(purchaseDeliveryRecordProduct.getPurchaseOrderDetailId());
                if (purchaseDeliveryRecordProduct.getQuantity()!=null) {
                    orderDetailServiceById.setHasDeliveryQuantity(orderDetailServiceById.getHasDeliveryQuantity().add(purchaseDeliveryRecordProduct.getQuantity()));
                }
                orderDetailServiceById.setUpdateTime(LocalDateTime.now());
                orderDetails.add(orderDetailServiceById);
            }
            purchaseDeliveryRecordProductService.saveBatch(purchaseDeliveryRecordForm.getPurchaseDeliveryRecordProducts());
            //修改采购订单详情 剩余发货数量
            purchaseOrderDetailService.updateBatchById(orderDetails);
            // 修改采购订单发货状态
            if(skuNum > 0){
                // 查询采购订单的产品是否全部发货
                AtomicReference<Boolean> isAllSend = new AtomicReference<>(true);
                QueryWrapper<PurchaseOrderDetail> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("purchase_order_id", purchaseDeliveryRecord.getPurchaseOrderId());
                queryWrapper.eq("is_deleted",false);
                List<PurchaseOrderDetail> list = purchaseOrderDetailService.list(queryWrapper);
                if (CollectionUtil.isNotEmpty(list)){
                    list.forEach(info->{
                        if (info.getHasDeliveryQuantity().compareTo(info.getNeedQuantity()) < 0){
                            isAllSend.set(false);
                        }
                    });
                    //如果全部发货完
                    if (isAllSend.get()){
                        purchaseOrder.setShippingStatus(PurchaseOrder.ShippingStatus.shipped);
                        purchaseOrderService.updateById(purchaseOrder);
                    }
                }
            }

        }
        return i;
    }

    @Override
    public int update(PurchaseDeliveryRecordForm purchaseDeliveryRecordForm) {
        //校验
        PurchaseDeliveryRecord purchaseDeliveryRecord = new PurchaseDeliveryRecord();
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(PurchaseDeliveryRecord.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(purchaseDeliveryRecordForm, purchaseDeliveryRecord, copyOptions);
        int i = baseMapper.updateById(purchaseDeliveryRecord);
        if (i > 0) {
            // 删除发货记录信息
            purchaseDeliveryRecordProductService.remove(Wrappers.<PurchaseDeliveryRecordProduct>query().lambda().eq(PurchaseDeliveryRecordProduct::getPurchaseDeliveryRecordId, purchaseDeliveryRecord.getId()));
            // 获取采购订单
            for (PurchaseDeliveryRecordProduct purchaseDeliveryRecordProduct : purchaseDeliveryRecordForm.getPurchaseDeliveryRecordProducts()) {
                purchaseDeliveryRecordProduct.setPurchaseDeliveryRecordId(purchaseDeliveryRecord.getId());
            }
            purchaseDeliveryRecordProductService.saveBatch(purchaseDeliveryRecordForm.getPurchaseDeliveryRecordProducts());
        }
        return i;
    }

    @Override
    public List<PurchaseDeliveryRecordVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<PurchaseDeliveryRecordVO> pageList4app(Page page, Map<String, Object> params) {
        List<PurchaseDeliveryRecordVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public PurchaseDeliveryRecordVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }

    /**
     * 查出供应商下的运单
     * @param supplierId
     * @return
     */
    @Override
    public List<SupplierWaybillVo> getWaybillInfoBy(String supplierId) {
        return baseMapper.getWaybillInfoBy(supplierId);
    }

    @Override
    public PurchaseDeliveryRecordVO detail(Long id) {
        String databaseUser = DynamicDataSource.USER_PREFIX;
        if (StringUtils.isNotBlank(DynamicDataSource.name.get())) {
            databaseUser = databaseUser + "-" + DynamicDataSource.name.get();
        }
        return baseMapper.detail(id,databaseUser);
    }
}
